<template>
  <div class="invite-friends-page">
    <van-nav-bar
      title="邀请好友"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="invite-content">
      <div class="invite-header">
        <canvas ref="qrcodeCanvas" class="invite-image"></canvas>
        <p class="invite-code">{{ inviteCode }}</p>
        <h2 class="invite-title">邀请好友，赢取奖励</h2>
        <p class="invite-description">邀请好友加入，双方都能获得丰厚奖励！</p>
      </div>
      <div class="invite-actions">
        <div class="invite-card" @click="shareToFriends('wechat')">
          <img src="../../../public/微信-01.png" alt="微信好友" />
          <span>微信好友</span>
        </div>
        <div class="invite-card" @click="shareToFriends('moments')">
          <img src="../../../public/朋友圈.png" alt="朋友圈" />
          <span>朋友圈</span>
        </div>
        <div class="invite-card" @click="shareToFriends('qq')">
          <img src="../../../public/QQ.png" alt="QQ好友" />
          <span>QQ好友</span>
        </div>
        <div class="invite-card" @click="shareToFriends('qzone')">
          <img src="../../../public/qq空间.png" alt="QQ空间" />
          <span>QQ空间</span>
        </div>
      </div>
      <van-button type="info" block @click="copyInviteCode">复制邀请码</van-button>
      <div class="invite-rules">
        <h3>活动规则</h3>
        <ul>
          <li>每邀请一位好友成功注册，您将获得奖励。</li>
          <li>好友注册后，需完成首次任务才能领取奖励。</li>
          <li>活动最终解释权归本公司所有。</li>
        </ul>
      </div>
      <div class="invite-input">
        <van-field v-model="inputCode" label="邀请码" placeholder="请输入邀请码" />
        <van-button type="primary" block @click="submitInviteCode">提交邀请码</van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Notify } from 'vant';
import QRCode from 'qrcode';

const route = useRoute();
const router = useRouter();

// 点击返回按钮
const onClickLeft = () => {
  router.back();
};

// 平台分享函数
const shareToFriends = (platform: string) => {
  const inviteLink = `https://example.com/invite?code=${inviteCode.value}`;
  switch (platform) {
    case 'wechat':
      window.location.href = `weixin://dl/business/?t=${encodeURIComponent(inviteLink)}`;
      break;
    case 'moments':
      window.location.href = `weixin://dl/moments/?t=${encodeURIComponent(inviteLink)}`;
      break;
    case 'qq':
      window.location.href = `mqqapi://share/to_fri?src_type=web&version=1&file_type=news&url=${encodeURIComponent(inviteLink)}`;
      break;
    case 'qzone':
      window.open(`http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${encodeURIComponent(inviteLink)}`, '_blank');
      break;
    default:
    new  Notify({ type: 'warning', message: `分享至${platform}功能暂未实现` });
  }
};
// 复制邀请码
const copyInviteCode = () => {
  navigator.clipboard.writeText(inviteCode.value).then(() => {
   new Notify({ type: 'success', message: '邀请码已复制' });
  }).catch(() => {
   new Notify({ type: 'danger', message: '复制失败，请重试' });
  });
};

// 提交邀请码
const submitInviteCode = () => {
  if (inputCode.value === inviteCode.value) {
    new Notify({ type: 'success', message: '邀请码提交成功' });
  } else {
    new Notify({ type: 'danger', message: '邀请码错误，请重试' });
  }
};

// 生成邀请码函数
const generateInviteCode = () => {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let code = '';
  for (let i = 0; i < 11; i++) {
    code += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return code;
};

// 定义响应式变量
const inviteCode = ref<string>('');
const inputCode = ref('');

// 生成二维码
const qrcodeCanvas = ref<HTMLCanvasElement | null>(null);

const generateQRCode = (link: string) => {
  if (qrcodeCanvas.value) {
    QRCode.toCanvas(qrcodeCanvas.value, link, { width: 150, height: 150 }, (error) => {
      if (error) console.error(error);
    });
  }
};

onMounted(() => {
  const storedInviteCode = localStorage.getItem('inviteCode');
  if (storedInviteCode) {
    inviteCode.value = storedInviteCode;
  } else {
    inviteCode.value = generateInviteCode();
    localStorage.setItem('inviteCode', inviteCode.value);
  }

  const inviteLink = `https://example.com/invite?code=${inviteCode.value}`;
  generateQRCode(inviteLink);
});

// 页面重新加载时
watch(
  () => route.fullPath,
  () => {
    inviteCode.value = generateInviteCode();
    localStorage.setItem('inviteCode', inviteCode.value);
    const inviteLink = `https://example.com/invite?code=${inviteCode.value}`;
    generateQRCode(inviteLink);
  },
  { immediate: true }
);
</script>

<style scoped>
.invite-friends-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}
.invite-content {
  flex: 1;
  padding: 16px;
  background-color: #fff;
}
.invite-header {
  text-align: center;
  margin-bottom: 24px;
}
.invite-image {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  margin-bottom: 16px;
}
.invite-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}
.invite-description {
  font-size: 16px;
  color: #666;
}
.invite-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
}
.invite-card {
  width: 22%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
  cursor: pointer;
  text-align: center;
}
.invite-card img {
  width: 56px;
  height: 56px;
  margin-bottom: 8px;
}
.invite-card span {
  font-size: 14px;
  color: #333;
}
.invite-rules {
  background-color: #f9f9f9;
  padding: 16px;
  border-radius: 8px;
}
.invite-rules h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.invite-rules ul {
  list-style-type: disc;
  padding-left: 20px;
}
.invite-rules li {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}
.invite-input {
  margin-top: 24px;
}
.invite-input .van-field {
  margin-bottom: 16px;
}
.invite-code {
  font-size: 20px;
  font-weight: bold;
  color: #ea3d3d;
  margin-top: 16px;
  text-align: center;
}
</style>
